import React, {memo, useEffect, useState} from 'react';
import MusicDetailsStyle from "./IndexStyle";
import {Button, Drawer, message, Modal} from "antd";
import UnitBox from "../../../../components/part/unitBox/UnitBox";
import {getMusicByIdAPI} from "../../../../services/music";
import {MusicInsertDTO} from "../../../../interface/MusicInterface";
import getLrc from "../../../../utils/lrcExtract";
import {getHourMineSecondBySecond} from "../../../../utils/timeFormatting";
import {deleteLogicCollectMusicApi, getCollectMusicListApi, insertCollectMusicApi} from "../../../../services/collect";
import {deleteFavoriteApi, getFavoriteMusicCollectApi, insertFavoriteApi} from "../../../../services/favoriteCount";
import {format} from "../../../../utils/dateFormat";
import {setMusicId2LocalStorage} from "../../../../utils/projectFunction";
import {useNavigate} from "react-router-dom";
import {MusicCollect} from "../../../../interface/MusicCollectInterface";
import {getMusicCollectPageApi, insertMusicCollectOfMusicListApi} from "../../../../services/musicCollect";
import MusicCoverItem from "../../../../components/part/musicCoverItem/MusicCoverItem";
import SongSheetItem from "../../../../components/part/songSheetItem/SongSheetItem";
/**
 * 音乐详情页
 */
type Props = {
  id:number,
};

const MusicDetailsCover=memo(function (props:Props) {
  const [cover,setCover]=useState("");
  useEffect(() => {
    getMusicByIdAPI(props.id).then((result:any)=>{
      setCover(result.data.data.cover);
    },(error)=>{
      console.log(error);
    });
  }, []);
  return (
    <MusicDetailsStyle $cover={cover}>
      <div className="music-details-cover"></div>
    </MusicDetailsStyle>
  );
});
const MusicDetailsInfo=memo(function (props: Props) {
  const navigate=useNavigate();
  const [messageApi, contextHolder] = message.useMessage();
  const [open, setOpen] = useState(false);
  /** 获取用户id */
  const userId=parseInt(localStorage.getItem("yf_gaduation_zzmusic_user_id") as string);
  /** 用户收藏的音乐列表 */
  const [musicList,setMusicList]=useState<MusicInsertDTO[]>([]);
  /** 音乐详情 */
  const [music,setMusic]=useState<MusicInsertDTO>();
  /** 用户创建的歌单 */
  const [userCreateCollect,setUserCreateCollect]=useState<MusicCollect[]>([]);



  useEffect(() => {
    /** 获取音乐详情 */
    getMusicByIdAPI(props.id).then((result:any)=>{
      // console.log(result);
      setMusic(result.data.data);
    },(error)=>{
      console.log(error);
    });
    /** 获取用户关注列表 */
    getCollectMusicListApi({userId,isDelete:0}).then((result:any)=>{
      // console.log(result);
      setMusicList(result.data.data.data);
    },(error)=>{
      console.log(error);
    });

    /** 获取用户创建的列表 */
    getMusicCollectPageApi({createUserId:userId}).then((result:any)=>{
      console.log(result);
      setUserCreateCollect(result.data.data.data);
    },(error)=>{
      console.log(error);
    });

  }, []);

  /** 播放按钮 */
  function playBtn(){
    setMusicId2LocalStorage(props.id);
    navigate("/musicplayer");
  }

  /** 下载方法 */
  function musicDownload() {
    window.open(music?.url);
  }

  /** 添加到歌单 回调方法 */
  function insertMusicCollect(id:number) {
    insertMusicCollectOfMusicListApi({musicCollectId:id,musicId:props.id}).then((result:any)=>{
      console.log(result.data.code);
      if (result.data.code===200){
        messageApi.open({
          type:"success",
          content:"添加成功",
        })
      }else{
        messageApi.open({
          type:"error",
          content:"添加失败",
        });
      }
      onClose();
    },(error)=>{
      console.log(error);
    });
  }

  /** 添加收藏 */
  function insertFavoriteBtn() {
    insertCollectMusicApi({userId,targetId:props.id}).then((result:any)=>{
      if (result.data.code===200){
        messageApi.open({
          type:"success",
          content:"收藏成功"
        });
        /** 此时再重新请求喜欢的列表 */
        getCollectMusicListApi({userId,isDelete:0}).then((result:any)=>{
          setMusicList(result.data.data.data);
        },(error)=>{
          console.log(error);
        });
      }
    },(error)=>{
      console.log(error);
    });
  }

  /** 取消收藏 */
  function deleteFavoriteBtn() {
    deleteLogicCollectMusicApi({userId,targetId:props.id}).then((result:any)=>{
      console.log(result);
      if (result.data.code===200){
        messageApi.open({
          type:"success",
          content:"取消收藏成功"
        });
        //此时再重新请求喜欢的列表
        getFavoriteMusicCollectApi({type:1,userId}).then((result:any)=>{
          setMusicList(result.data.data.data);
        },(error)=>{
          console.log(error);
        });
      }
    },(error)=>{
      console.log(error);
    });
  }


  /** 打开侧边栏 */
  const showDrawer = () => {
    setOpen(true);
  };

  /** 关闭侧边栏 */
  const onClose = () => {
    setOpen(false);
  };


  return (
    <MusicDetailsStyle>
      {contextHolder}
      <div className="info-title">{music?.name}</div>
      <div className="create-username iconfont">&#xe658; &nbsp;&nbsp;{music?.singerName}</div>
      <div className="info-box">
        <div>专辑: {music?.albumName}</div>
        <div>语种: {music?.type}</div>
        <div>时长: {getHourMineSecondBySecond(music?.timer as number)}</div>
        <div>发行时间: {format(music?.sendTimer)}</div>
      </div>
      <div className="btn-list-box">
        <Button className="iconfont album-details-btn select-btn" onClick={playBtn}>&#xe87c; 播放</Button>
        {
          musicList.some((value)=>{
            return value.musicId===props.id;
          })?
            <Button className="iconfont album-details-btn select-btn" onClick={deleteFavoriteBtn}>&#xe86f; 已收藏</Button>
            :
            <Button className="iconfont album-details-btn" onClick={insertFavoriteBtn}>&#xe86f; 收藏</Button>
        }
        {/*<Button className="iconfont album-details-btn">&#xe86f; 收藏</Button>*/}
        <Button className="iconfont album-details-btn" onClick={musicDownload}>&#xe606; 下载</Button>
        <Button className="iconfont album-details-btn" onClick={showDrawer}>&#xe604; 添加到</Button>
        <Button className="iconfont album-details-btn">&#xe891; 评论</Button>

        <Drawer title="添加到歌单" onClose={onClose} open={open}>

          {
            userCreateCollect.map((value)=>{
              return ( <SongSheetItem
                songName={value.name}
                size={160}
                coverUrl={value.cover}
                id={value.musicCollectId}
                callbackFunc={insertMusicCollect}
              />)
            })
          }

        </Drawer>

      </div>

    </MusicDetailsStyle>
  );
});
const MusicDetailsContent=memo(function (props: Props) {
  const [music,setMusic]=useState<MusicInsertDTO>();
  useEffect(() => {
    getMusicByIdAPI(props.id).then((result:any)=>{
      console.log(result);
      setMusic(result.data.data);
    },(error)=>{
      console.log(error);
    });
  }, []);
  return (
    <MusicDetailsStyle>
      <UnitBox size={24} title={"歌词"} isLeft={true}>
        <ul className="music-details-content-box">
          {
            getLrc(music?.lyric as string).map((item,index)=>{
              return (<li key={index}>{item.content}</li>)
            })
          }
        </ul>
      </UnitBox>
    </MusicDetailsStyle>
  );
});
const MusicDetailsSidebar=memo(function (props: Props) {
  return (
    <MusicDetailsStyle>
      {/*<UnitBox*/}
      {/*  color={"#000"}*/}
      {/*  title={"简介"}*/}
      {/*  size={20}*/}
      {/*  isLeft={true}*/}
      {/*>*/}
      {/*  <div className="album-details-sidebar-info">*/}
      {/*  </div>*/}
      {/*</UnitBox>*/}
    </MusicDetailsStyle>
  );
});


export {MusicDetailsCover, MusicDetailsInfo,MusicDetailsContent,MusicDetailsSidebar};
